#pragma once
#include <pthread.h>
#include <semaphore.h>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>
#include <cstdlib>
#include <vector>
static const int defaultcap = 5;

template <class T>
class RingQueue
{
private:
    void P(sem_t &sem)
    {
        sem_wait(&sem);
    }

    void V(sem_t &sem)
    {
        sem_post(&sem);
    }

    void Lock(pthread_mutex_t &mutex)
    {
        pthread_mutex_lock(&mutex);
    }

    void Unlock(pthread_mutex_t &mutex)
    {
        pthread_mutex_unlock(&mutex);
    }

public:
    RingQueue(int cap = defaultcap)
        : ringqueue_(cap), cap_(cap), c_step(0), p_step(0)
    {
        pthread_mutex_init(&c_mutex_, nullptr);
        pthread_mutex_init(&p_mutex_, nullptr);

        sem_init(&cdata_sem, 0, 0);
        sem_init(&pspace_sem, 0, cap);
    }

    void Push(const T &in)
    {
        P(pspace_sem);
        Lock(p_mutex_);
        ringqueue_[p_step] = in;
        p_step++;
        p_step %= cap_;
        Unlock(p_mutex_);
        V(cdata_sem);
    }

    void Pop(T *out)
    {
        P(cdata_sem);
        Lock(c_mutex_);
        *out = ringqueue_[c_step++];
        c_step %= cap_;
        Unlock(c_mutex_);
        V(pspace_sem);
    }
    ~RingQueue()
    {
        sem_destroy(&cdata_sem);
        sem_destroy(&pspace_sem);

        pthread_mutex_destroy(&c_mutex_);
        pthread_mutex_destroy(&p_mutex_);
    }

private:
    std::vector<T> ringqueue_;
    int cap_;

    int c_step;
    int p_step;

    pthread_mutex_t c_mutex_;
    pthread_mutex_t p_mutex_;

    sem_t cdata_sem;
    sem_t pspace_sem;
};